package com.hspedu.lambda2;

import org.junit.Test;

import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 方法引用的使用
 *
 * Created by shkstart.
 */
@SuppressWarnings("all")
public class MethodRefTest {

	// 情况一：对象 :: 实例方法
	//Consumer中的void accept(T t)
	//PrintStream中的void println(T t)
	@Test
	public void test1() {
		Consumer<String> consumer = str -> System.out.println(str);
		consumer.accept("北京");

		//方法引用
		PrintStream ps = System.out;
		Consumer<String> consumer1 = ps :: println;
		consumer1.accept("hello");
	}
	
	//Supplier中的T get()
	//Employee中的String getName()
	@Test
	public void test2() {
		Employee emp = new Employee(1001, "Tom", 23, 5600);
		Supplier<String> stringSupplier = () -> emp.getName();

		Supplier<String> stringSupplier1 = emp :: getName;
		stringSupplier1.get();
	}

	// 情况二：类 :: 静态方法
	//Comparator中的int compare(T t1,T t2)
	//Integer中的int compare(T t1,T t2)
	@Test
	public void test3() {
		Comparator<Integer> comparator = (t1, t2) -> Integer.compare(t1,t2);
		comparator.compare(1,2);

		Comparator<Integer> comparator1 = Integer::compare;
		comparator1.compare(2,3);
	}
	
	//Function中的R apply(T t)
	//Math中的Long round(Double d)
	@Test
	public void test4() {
		Function<Double,Long> func1 = new Function<Double, Long>() {
			@Override
			public Long apply(Double aDouble) {
				return Math.round(aDouble);
			}
		};

		Function<Double,Long> func2 = d -> Math.round(d);
		func2.apply(2.3);
		Function<Double,Long> func3 = Math :: round;
		func3.apply(4.4);
	}

	// 情况三：类 :: 实例方法 
	// Comparator中的int comapre(T t1,T t2)
	// String中的int t1.compareTo(t2)
	@Test
	public void test5() {
		Comparator<String> comparator1 = (s1 , s2) -> s1.compareTo(s2);
		System.out.println(comparator1.compare("abc", "abd"));

		Comparator<String> comparator2 = String :: compareTo;
		System.out.println(comparator2.compare("abc", "abd"));
	}

	//BiPredicate中的boolean test(T t1, T t2);
	//String中的boolean t1.equals(t2)
	@Test
	public void test6() {
		BiPredicate<String,String> pre1 = (s1, s2) -> s1.equals(s2);
		System.out.println(pre1.test("abc", "abd"));

		BiPredicate<String,String> pre2 = String :: equals;
		System.out.println(pre2.test("abc", "abm"));
	}
	
	// Function中的R apply(T t)
	// Employee中的String getName();
	@Test
	public void test7() {
		Function<Employee,String> func1 = e -> e.getName();
		System.out.println(func1.apply(new Employee(1001, "tom", 23, 1000)));

		Function<Employee,String> func2 = Employee::getName;
		System.out.println(func2.apply(new Employee(1002, "tom2", 233, 10002)));
	}

}
